<template>
    <div class="ma-content-block lg:flex justify-between p-4">
        <div class="app-container">
            <div class="account-num">
                <div>
                    <span>{{ $t('basics.normalAcc') }}：</span>
                    <span class="num_red">{{ accNum.num_of_useable }}</span>
                </div>
                <div>
                    <span>{{ $t('basics.bannedAcc') }}：</span>
                    <span class="num_red">{{ accNum.num_of_cannot_use }}</span>
                </div>
                <div>
                    <span>{{ $t('basics.assignedAcc') }}：</span>
                    <span class="num_red">{{
                        accNum.num_of_has_use_user
                    }}</span>
                </div>
                <div>
                    <span>{{ $t('basics.undistributedAcc') }}：</span>
                    <span class="num_red">{{ accNum.num_of_no_use_user }}</span>
                </div>
                <div>
                    <span>{{ $t('basics.serviceAccounts') }}：</span>
                    <span class="num_red">{{
                        accNum.num_of_customer_service
                    }}</span>
                </div>
            </div>
            <div class="container-header mt10">
                <div class="container-header-tr">
                    <div>
                        <span style="width: 40px" class="s1">{{
                            $t('basics.account')
                        }}</span>
                        <a-input
                            v-model="form.myphonenumber"
                            :placeholder="$t('basics.accountText')"
                        />
                    </div>
                    <div>
                        <span class="s1">{{ $t('basics.status') }}</span>
                        <a-select
                            style="width: 120px"
                            v-model="form.status"
                            :placeholder="$t('basics.textStatus')"
                            allow-clear
                        >
                            <a-option
                                :label="$t('basics.zhengchang')"
                                :value="1"
                            ></a-option>
                            <a-option
                                :label="$t('basics.fengjin')"
                                :value="2"
                            ></a-option>
                        </a-select>
                    </div>
                    <div>
                        <span class="s1">{{ $t('basics.typeTxt') }}</span>
                        <a-select
                            style="width: 120px"
                            v-model="form.phoneinfo_type"
                            :placeholder="$t('basics.pleaseTypeTxt')"
                            allow-clear
                        >
                            <a-option
                                :label="$t('basics.whole')"
                                :value="0"
                            ></a-option>
                            <a-option label="tn" value="tn"></a-option>
                            <a-option label="tf" value="tf"></a-option>
                        </a-select>
                    </div>
                    <div>
                        <span style="width: 80px" class="s1">{{
                            $t('basics.editAcc')
                        }}</span>
                        <a-input
                            v-model="form.use_username"
                            :placeholder="$t('basics.textAcc')"
                        />
                    </div>
                    <div>
                        <span class="s1">{{ $t('basics.AccRadius') }}</span>
                        <a-range-picker
                            style="width: 280px"
                            v-model="form.created_at"
                            @change="onChange"
                        />
                    </div>
                    <div>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="searchButton"
                        >
                            <icon-search class="mr6" />
                            {{ $t('basics.search') }}
                        </a-button>
                        <a-button type="secondary" @click="resetButton">
                            <icon-refresh class="mr6" />
                            {{ $t('basics.reset') }}
                        </a-button>
                    </div>
                </div>
                <div class="container-header-tr mt10 mb10">
                    <div>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="updataAcc"
                        >
                            <icon-cloud-download class="mr6" />
                            {{ $t('basics.uplaodAcc') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            status="danger"
                            @click="changeSatusList"
                        >
                            <icon-exclamation-circle-fill class="mr6" />
                            {{ $t('basics.bandAcc') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            status="danger"
                            @click="deleteAcc(0)"
                        >
                            <icon-delete class="mr6" />
                            {{ $t('basics.deleteAcc') }}
                        </a-button>
                        <a-button
                            class="mr20"
                            type="primary"
                            @click="exportAcc"
                        >
                            <icon-cloud-download class="mr6" />
                            {{ $t('basics.exportData') }}
                        </a-button>
                    </div>
                </div>
            </div>
            <div class="container-content">
                <div class="container-content-table">
                    <a-table
                        :stripe="true"
                        :columns="columns"
                        :data="tableList"
                        :loading="loading"
                        :row-selection="rowSelection"
                        v-model:selectedKeys="selectedKeys"
                        row-key="id"
                        @selection-change="getRowData"
                        :pagination="false"
                    >
                        <template #myphonenumber="{ record }">
                            <a-tooltip
                                :content="$t('basics.copy')"
                                position="bottom"
                            >
                                <i
                                    class="copy-icon"
                                    @click="
                                        copyToClipboard(record.myphonenumber)
                                    "
                                    ><icon-copy
                                /></i>
                            </a-tooltip>
                            <span>{{ record.myphonenumber }}</span>
                        </template>
                        <template #status="{ record }">
                            <a-popconfirm
                                :content="
                                    $t('basics.confirmEdit') +
                                    (record.status == 1
                                        ? $t('basics.openTxt')
                                        : $t('basics.offTxt')) +
                                    $t('basics.whatTxt')
                                "
                                @ok="statusChange(record)"
                            >
                                <a-switch
                                    v-model="record.status"
                                    :checked-value="1"
                                    :unchecked-value="2"
                                />
                            </a-popconfirm>
                        </template>

                        <template #is_customer_service="{ record }">
                            {{ record.is_customer_service ? '是' : '否' }}
                        </template>
                        <template #operate="{ record }">
                            <a-link @click="deleteAcc(record.id)">
                                {{ $t('basics.delete') }}</a-link
                            >
                            <a-link @click="detail(record.id)">
                                {{ $t('basics.xiangqing') }}</a-link
                            >
                        </template>
                        <template #cookie="{ record }">
                            <a-tooltip
                                :content="$t('basics.copy')"
                                position="bottom"
                            >
                                <i
                                    class="copy-icon"
                                    @click="copyToClipboard(record.cookie)"
                                    ><icon-copy
                                /></i>
                            </a-tooltip>
                            <span>{{ record.cookie }}</span>
                        </template>
                        <template #device_info="{ record }">
                            <a-tooltip
                                :content="$t('basics.copy')"
                                position="bottom"
                            >
                                <i
                                    class="copy-icon"
                                    @click="copyToClipboard(record.device_info)"
                                    ><icon-copy
                                /></i>
                            </a-tooltip>
                            <span>{{ record.device_info }}</span>
                        </template>
                    </a-table>
                    <div
                        class="_crud-footer mt-3 text-right"
                        ref="crudFooterRef"
                    >
                        <a-pagination
                            :total="pageList.total"
                            show-total
                            show-jumper
                            show-page-size
                            @page-size-change="getList"
                            @change="getList"
                            v-model:current="form.page"
                            v-model:page-size="form.pageSize"
                            style="display: inline-flex"
                            :page-size-options="[10, 20, 50, 100]"
                            :default-page-size="10"
                        />
                    </div>
                </div>
            </div>
            <a-modal
                v-model:visible="tableModel.visibleUpdata"
                :render-to-body="false"
                :footer="false"
            >
                <template #title>
                    {{ $t('basics.uplaodAcc') }}
                </template>
                <a-form
                    :model="updataForm"
                    ref="updataFormRef"
                    :rules="upDatarules"
                >
                    <a-form-item
                        field="username"
                        :label="$t('basics.allotAcc')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            v-model="updataForm.username"
                            :placeholder="$t('basics.allotAccText')"
                        />
                    </a-form-item>
                    <a-form-item
                        field="project_id"
                        :label="$t('basics.allotPro')"
                        label-col-flex="80px"
                        validate-trigger="change"
                    >
                        <a-select
                            v-model="updataForm.project_id"
                            :style="{ width: '320px' }"
                            :placeholder="$t('basics.allotProText')"
                        >
                            <a-option
                                v-for="item in projectList"
                                :label="item.project_name"
                                :value="item.id"
                            ></a-option>
                        </a-select>
                    </a-form-item>
                    <a-upload draggable action="/" />
                </a-form>
                <div class="dialog-foot">
                    <a-button @click="handleUpdataCancel">{{
                        $t('basics.concel')
                    }}</a-button>
                    <a-button
                        type="primary"
                        @click="handleUpdataOk"
                        style="margin-right: 20px"
                        >{{ $t('basics.sure') }}</a-button
                    >
                </div>
            </a-modal>
            <a-modal
                v-model:visible="exportVisible"
                :render-to-body="false"
                :footer="false"
            >
                <template #title>
                    {{ $t('basics.exportData') }}
                </template>
                <a-form
                    :model="exportForm"
                    ref="exportFormRef"
                    :rules="exportrules"
                >
                    <a-form-item
                        field="num_of_export"
                        :label="t('basics.daochushuliang')"
                        label-col-flex="80px"
                        validate-trigger="blur"
                    >
                        <a-input
                            style="width: 100%; margin-right: 20px"
                            v-model="exportForm.num_of_export"
                            :placeholder="t('basics.daochushuliang')"
                            type="number"
                        />
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button
                        style="color: #000"
                        class="mr20"
                        @click="exportVisible = false"
                        >{{ $t('basics.concel') }}</a-button
                    >
                    <a-button
                        class="mr20"
                        type="primary"
                        @click="exporthandleOk"
                        ><a-link :hoverable="false">{{
                            $t('basics.sure')
                        }}</a-link></a-button
                    >
                </div>
            </a-modal>
            <a-modal
                v-model:visible="tableModel.detailVisible"
                :render-to-body="false"
                :footer="false"
                width="800px"
            >
                <template #title>{{ $t('basics.xiangqing') }}</template>
                <a-form :model="tableModel.detailData">
                    <a-form-item
                        v-for="item of detailShowFields"
                        :field="item.fields"
                        :label="item.title + ' :'"
                        label-col-flex="135px"
                        validate-trigger="blur"
                    >
                        <a-typography-paragraph
                            v-if="item.fields === 'is_send_finish'"
                            >{{
                                tableModel.detailData[item.fields] ? '是' : '否'
                            }}</a-typography-paragraph
                        >
                        <a-typography-paragraph
                            v-else-if="
                                item.child != '' &&
                                tableModel.detailData[item.fields]
                            "
                            :copyable="
                                item.fields == 'cookie' ||
                                item.fields == 'device_info' ||
                                item.fields == 'proxy_ip' ||
                                item.fields == 'phoneinfo_tn_extend'
                            "
                            >{{
                                tableModel.detailData[item.fields][item.child]
                            }}</a-typography-paragraph
                        >
                        <a-typography-paragraph
                            v-else
                            :copyable="
                                item.fields == 'cookie' ||
                                item.fields == 'device_info' ||
                                item.fields == 'proxy_ip' ||
                                item.fields == 'phoneinfo_tn_extend'
                            "
                            >{{
                                tableModel.detailData[item.fields]
                            }}</a-typography-paragraph
                        >
                    </a-form-item>
                </a-form>
                <div class="dialog-foot">
                    <a-button
                        class="mr20"
                        @click="tableModel.detailVisible = false"
                        >{{ $t('basics.close') }}</a-button
                    >
                </div>
            </a-modal>
            <ma-import
                :render-to-body="false"
                ref="crudImportRef"
                :upLoadData="importFile"
                @success="refresh"
                :isShowLoad="true"
                :downLoadData="downFile"
            />
        </div>
    </div>
</template>
<script setup>
import { ref, reactive, getCurrentInstance } from 'vue';
import { $request } from '@/utils/request.js';
import MaImport from '@/components/import/index.vue';
import commonApi from '@/api/common';
import tool from '@/utils/tool';
import { Message } from '@arco-design/web-vue';
import {
    getPhoneinfoList,
    getProjectList,
    changeStatus,
    deleteAccount,
    changeStatusList,
    getAmountList
} from '@/api/cloud/cloudPhoneinfo.js';
import { useI18n } from 'vue-i18n';
const tableModel = reactive({
    detailData: {}, //详情
    // 控制对话框
    visible: false,
    visibleUpdata: false,
    detailVisible: false
});
const { proxy } = getCurrentInstance();
const { t } = useI18n();
const selectedKeys = ref([]);
const rowSelection = ref({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
});
const exportForm = ref({});
const exportVisible = ref(false);
const exportFormRef = ref('');
// 选中行的list
const updataFormRef = ref('');
const loading = ref(false);
const crudImportRef = ref('');
// 控制对话框
// const visible = ref(false);
// const visibleUpdata = ref(false);
// 绑定项目表单
const pageList = ref({
    total: 0
});
// 账号数量
const accNum = ref({});
const updataForm = ref({});
const columns = [
    {
        title: t('basics.xuhao'),
        dataIndex: 'id',
        width: 90,
        slotName: 'id'
    },
    {
        title: t('basics.zhanghao'),
        dataIndex: 'myphonenumber',
        width: 150,
        slotName: 'myphonenumber',
        ellipsis: true,
        tooltip: true
    },
    {
        title: t('basics.typeTxt'),
        dataIndex: 'phoneinfo_type',
        width: 70,
        slotName: 'phoneinfo_type',
        ellipsis: true,
        tooltip: true
    },
    {
        title: '客服系统',
        dataIndex: 'is_customer_service',
        width: 90,
        slotName: 'is_customer_service',
        ellipsis: true,
        tooltip: true
    },
    {
        title: 'cookie',
        dataIndex: 'cookie',
        ellipsis: true,
        tooltip: true,
        width: 150,
        slotName: 'cookie'
    },
    {
        title: 'device_info',
        dataIndex: 'device_info',
        ellipsis: true,
        tooltip: true,
        width: 150,
        slotName: 'device_info'
    },

    {
        title: t('basics.suoshuyonghu'),
        dataIndex: 'owner',
        width: 100,
        slotName: 'owner'
    },
    {
        title: t('basics.fasongshuliang'),
        dataIndex: 'send_count',
        width: 100,
        slotName: 'send_count'
    },
    {
        title: t('basics.huifushuliang'),
        dataIndex: 'num_of_reply',
        width: 100,
        slotName: 'num_of_reply'
    },
    {
        title: t('basics.status'),
        dataIndex: 'status',
        width: 80,
        slotName: 'status'
    },
    // {
    //     title: t('basics.shangcifasong'),
    //     dataIndex: 'last_send_unixtime',
    //     width: 180,
    //     ellipsis: true,
    //     tooltip: true,
    //     slotName: 'last_send_unixtime'
    // },
    {
        title: t('basics.chuangjianshijian'),
        dataIndex: 'created_at',
        width: 180,
        ellipsis: true,
        tooltip: true,
        slotName: 'created_at'
    },
    {
        title: t('basics.controls'),
        dataIndex: 'operate',
        width: 100,
        slotName: 'operate'
    }
];
/**详情展示字段 */
const detailShowFields = [
    {
        title: 'user_name',
        fields: 'user_name',
        child: ''
    },
    {
        title: 'myphonenumber',
        fields: 'myphonenumber',
        child: ''
    },
    {
        title: '是否发送完成',
        fields: 'is_send_finish',
        child: ''
    },
    {
        title: '上次查询回复时间戳',
        fields: 'last_select_reply_unixtime',
        child: ''
    },
    {
        title: '上次发送时间',
        fields: 'last_send_unixtime',
        child: ''
    },
    {
        title: 'cookie',
        fields: 'cookie',
        child: ''
    },
    {
        title: 'device_info',
        fields: 'device_info',
        child: ''
    },
    {
        title: '代理ip',
        fields: 'proxy_ip',
        child: ''
    },
    {
        title: '发送ip',
        fields: 'phoneinfo_tn_extend',
        child: 'send_ip'
    }
];
const form = ref({
    username: '',
    myphonenumber: '',
    use_username: '',
    project_id: '',
    created_at: [],
    status: '',
    page: 1,
    pageSize: 10,
    phoneinfo_type: ''
});
const upDatarules = ref({
    username: [
        {
            required: true,
            message: t('basics.warnAcc')
        }
    ],
    project_id: [
        {
            required: true,
            message: t('basics.warnPro')
        }
    ]
});
const exportrules = ref({
    num_of_export: [
        {
            required: true,
            message: t('basics.daoshuNum')
        }
    ]
});
// 获取选择列
const getRowData = (selectedRowKeys) => {};
const tableList = ref([]);
// 获取列表数据
const getList = () => {
    loading.value = true;
    let params = {
        ...form.value,
        phoneinfo_type: form.value.phoneinfo_type || undefined
    };
    getPhoneinfoList(params).then((res) => {
        tableList.value = res.data.items;
        pageList.value = res.data.pageInfo;
        loading.value = false;
    });
};

const getAmount = () => {
    getAmountList().then((res) => {
        accNum.value = res.data;
    });
};

// 获取项目列表
const projectList = ref([]);
const getProject = () => {
    getProjectList().then((res) => {
        projectList.value = res.data.items;
    });
};
// 搜索
const searchButton = () => {
    getList();
};
// 选择时间
const onChange = (dateString, date) => {
    console.log(dateString, date);
};
const reset = () => {
    form.value.username = '';
    form.value.myphonenumber = '';
    form.value.status = '';
    form.value.project_id = '';
    form.value.phoneinfo_type = '';
    (form.value.created_at = []), (form.value.use_username = '');
    form.value.page = 1;
    form.value.pageSize = 10;
};
const resetButton = () => {
    reset();
    getAmount();
    getList();
};
// 复制文本
const copyToClipboard = (text) => {
    const el = document.createElement('textarea');
    el.value = text;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    proxy.$message.success(t('basics.fuzhisecess'));
};
// 状态改变
const statusChange = (row) => {
    changeStatus({ id: row.id, status: row.status })
        .then((res) => {
            if (res.code == 200) {
                proxy.$message.success(t('basics.updataSecc'));
            }
        })
        .catch((error) => {
            row.status = row.status == 1 ? 2 : 1;
        });
};
// 批量修改状态
const changeSatusList = () => {
    if (!selectedKeys.value.length) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    proxy.$modal.warning({
        title: t('basics.xitongtishi'),
        content: t('basics.contentText'),
        hideCancel: false,
        cancelText: t('basics.concel'),
        okText: t('basics.sure'),
        simple: false,
        onOk: () => {
            changeStatusList({ ids: selectedKeys.value, status: 2 }).then(
                (res) => {
                    if (res.code == 200) {
                        proxy.$message.success(t('basics.controlsSecc'));
                        selectedKeys.value = [];
                        getList();
                    }
                }
            );
        }
    });
};

// 上传项目操作
const updataAcc = () => {
    crudImportRef.value.open();
};
const importFile = ref({
    url: 'cloud/phoneinfo/import'
});
const downFile = ref({
    url: 'cloud/phoneinfo/download'
});
//   导入成功后
const refresh = () => {
    getAmount();
    getList();
};
const handleUpdataOk = () => {
    proxy.$refs['updataFormRef'].validate((valid) => {
        if (!valid) {
            bandProject(updataForm.value)
                .then((res) => {
                    tableModel.visible = false;
                })
                .catch((error) => {});
        }
    });
};
// 删除
const deleteAcc = (id) => {
    if (!selectedKeys.value.length && !id) {
        proxy.$message.error(t('basics.pSelectAccount'));
        return;
    }
    proxy.$modal.warning({
        title: t('basics.xitongtishi'),
        content: t('basics.deleteContent'),
        hideCancel: false,
        cancelText: t('basics.concel'),
        okText: t('basics.sure'),
        simple: false,
        onOk: () => {
            if (id) {
                deleteAccount({ ids: [id] }).then((res) => {
                    if (res.code == 200) {
                        proxy.$message.success(t('basics.controlsSecc'));
                        getList();
                    }
                });
            } else {
                console.log(selectedKeys.value);
                deleteAccount({ ids: selectedKeys.value }).then((res) => {
                    if (res.code == 200) {
                        selectedKeys.value = [];
                        proxy.$message.success(t('basics.controlsSecc'));
                        getList();
                    }
                });
            }
        }
    });
};

/**详情-按钮 */
const detail = async (id) => {
    let res = await $request.get('/cloud/phoneinfo/detail', { id });
    tableModel.detailData = res;
    tableModel.detailVisible = true;
};
const handleUpdataCancel = () => {
    tableModel.visibleUpdata = false;
};
const exportAcc = () => {
    exportVisible.value = true;
};
const exporthandleOk = () => {
    proxy.$refs['exportFormRef'].validate((valid) => {
        if (exportForm.value.num_of_export > accNum.value.num_of_no_use_user) {
            return Message.error(t('basics.daoshutishi'));
        }
        if (!valid) {
            Message.info(t('basics.qingqiuxiazai'));
            const url = 'cloud/phoneinfo/export';
            if (/^(http|https)/g.test(url)) {
                window.open(url);
            } else {
                exportVisible.value = false;
                commonApi
                    .download(url, 'post', {
                        num_of_export: exportForm.value.num_of_export
                    })
                    .then((res) => {
                        getList();
                        getAmount();
                        tool.download(res);
                        Message.success(t('basics.qingqiuchenggong'));
                    })
                    .catch((error) => {});
            }
        }
    });
};

getList();
getAmount();
getProject();
</script>
<script>
export default { name: 'cloud:phoneinfo' };
</script>
<style lang="less" scoped>
@import url('@/style/layout.less');
.account-num {
    font-size: 16px;
    display: flex;
    align-items: center;
    -mox-flex-wrap: wrap;
    -webkit-flex-wrap: wrap;
    flex-wrap: wrap;
    .num_red {
        margin-right: 30px;
        color: red;
    }
}
</style>
